package middleware

import (
	"context"
	"sale-admin/internal/app/grpc/client"
	"sale-admin/internal/app/grpc/protoc/devicec"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/logx"
	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
)

// grpc验证token是否通过
func LocationTokenCheck() gin.HandlerFunc {
	return func(c *gin.Context) {
		deviceClient, clientErr := client.GetDeviceAdminClient()
		if clientErr != nil {
			logx.Error(context.Background(), "grpc device client error", logx.Err(clientErr))
			return
		}
		// GRPC获取设备的区域信息
		req := devicec.LocationTokenInfoReq{
			Token: c.Query("token"),
		}
		// 获取GRPC返回的数据
		locationRsp, err := deviceClient.GetLocationInfo(c, &req)
		// 返回错误
		logx.Info(context.Background(), "grpc locationTokenInforsp error", logx.Any("locationRsp", locationRsp))
		if err != nil {
			logx.Info(context.Background(), "grpc device client error", logx.Any("locationErr", err.Error()))
			c.Abort()
		}
		if locationRsp.Code == 0 {
			// 2. GRPC获取机器,并存储到上下文
			if locationRsp.RobotIds == "" {
				response.JSON(c, nil, errorx.New("请求token无效", -1))
				c.Abort()
				return
			}
			c.Set("robot_ids", locationRsp.RobotIds)
			c.Set("location_name", locationRsp.Name)
			c.Set("location_id", locationRsp.Id)
			// 鉴权通过
			c.Next()
		} else {
			response.JSON(c, nil, errorx.New("请求token无效", -1))
			// 不通过
			c.Abort()
			return
		}
	}
}
